package com.fq.rpc.util;

import org.I0Itec.zkclient.ZkClient;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author jifang
 * @since 16/8/14 上午11:05.
 */
public class ServiceImplMap {

    private static final ConcurrentMap<Class<?>, Object> map = new ConcurrentHashMap<>();

    private static final ZkClient zk;

    private static final String FIRST_LEVEL_PATH = "/mi.rpc";


    static {
        zk = new ZkClient(ConfigMap.getServer("zk.servers"));
    }


    private static void createNode(String first, String second, String dest) {

        if (!zk.exists(first)) {
            zk.createPersistent(first);
        }

        if (!zk.exists(first + "/" + second)) {
            zk.createPersistent(first + "/" + second);
        }

        zk.createEphemeral(first + "/" + second + "/" + dest);
    }

    public static void push(Class<?> inter, Object impl) {
        map.put(inter, impl);

        // 发布到ZK
        String ip;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            ip = null;
            e.printStackTrace();
        }
        int port = ServerSocketInstance.getServerSocket().getLocalPort();
        createNode(FIRST_LEVEL_PATH, inter.getName(), String.format("%s:%s", ip, port));
    }

    public static Object get(Class<?> inter) {
        return map.get(inter);
    }
}
